#include <xscript/xitemboolean.h>
#include <astree/xabstractsyntaxtreeif.h>

XAbstractSyntaxTreeIf::XAbstractSyntaxTreeIf(XTokenPtr inputToken):
    XAbstractSyntaxTreeN(inputToken) {
    setName(L"if");
}

bool XAbstractSyntaxTreeIf::invokeImpl(std::shared_ptr<XVariableTable> table) {
    auto condition = getChildAt(0);
    if (!condition->invoke(table))
        return false;

    if (condition->getResult() && condition->getResult()->asBoolean()) {
        auto value = condition->getResult()->asBoolean()->getValue();
        if (value) {
            auto statement = getChildAt(1);
            if (!statement->invoke(table))
                return false;

            if (statement->shouldBreak()) {
                invokeBreak = true;
            } else if (statement->shouldReturn()) {
                result = statement->getResult();
                invokeReturn = true;
            }
            return true;
        } else {
            invokeSibling = true;
        }
    }

    return true;
}

